const app = getApp();
const rtcroom = require('../../../utils/rtcroom.js');
const getlogininfo = require('../../../getlogininfo');

Page({
  data: {
    roomID: '',        
    roomname: '',       
    beauty: 5,
    muted: false,
    debug: false,
    inputMsg: '',   
    comment: [],    
    frontCamera: true,
    showRoom: false,
    createRoom: true,
  },

  onRoomEvent(e) {
    switch (e.detail.tag) {
      case 'recvTextMsg': {
        /**
             * res:
             * {
             *   roomID: roomInfo.roomID,
             *   userID: msg.fromAccountNick,
             *   nickName: msg.nickName,
             *   headPic: msg.headPic,
             *   textMsg: msg.content,
             *   time: msg.time
	         * }
             */
        console.log('收到消息:', e.detail.detail);
        let msg = JSON.parse(e.detail.detail);
        this.data.comment.push({
          content: msg.textMsg,
          name: msg.nickName,
          time: msg.time,
        });
        this.setData({
          comment: this.data.comment,
          toview: '',
        });
        // 滚动条置底
        this.setData({
          toview: 'scroll-bottom',
        });
        break;
      }
      case 'roomClosed': {
        /*
            房间关闭时会收到此通知，客户可以提示用户房间已经关闭，做清理操作
          */
        // 在房间内部才显示提示
        const detail = e.detail.detail;
        console.log('roomClose===============:', detail);
        const pages = getCurrentPages();
        setTimeout(() => {
          if (pages.length > 1 && pages[pages.length - 1].__route__ === 'cm_video_alarm/trtc/pages/medical/room/room') {
            wx.navigateBack();
          }
        }, 1000);
        break;
      }
      case 'error': {
        // 在房间内部才显示提示
        console.error('error:', e.detail.detail);
        let pages = getCurrentPages();
        if (pages.length > 1 && (pages[pages.length - 1].__route__ === 'cm_video_alarm/trtc/pages/medical/room/room')) {
          wx.showModal({
            title: '系统提示',
            content: e.detail.detail,
            showCancel: false,
            complete: (result) => {
              pages = getCurrentPages();
              // 点击 modal 后，判断页面是否已跳转，防止跳转两次
              if (pages.length > 1 && pages[pages.length - 1].__route__ === 'cm_video_alarm/trtc/pages/medical/room/room') {
                wx.navigateBack();
              }
            },
          });
        }
        break;
      }
    }
  },

  onReady() {

    if (!this.versiongt(wx.systemInfo.SDKVersion, '2.7.7')) {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，影响正常使用，请升级到最新微信版本后再试。',
        showCancel: false,
        success: res => {
          wx.navigateBack();
        },
      });
      return;
    }

    wx.showLoading({
      title: '登录信息获取中',
    });
    getlogininfo.getLoginInfo({
      type: 'multi_room',
      success: ret => {
        this.getRoomId();
        wx.hideLoading();
      },
      fail: ret => {
        wx.hideLoading();
        wx.showModal({
          title: '获取登录信息失败',
          content: ret.errMsg,
          showCancel: false,
          complete: function () {
            wx.navigateBack();
          },
        });
      },
    });
  },

  onShow() {
    wx.setKeepScreenOn({
      keepScreenOn: true,
    });
    this.checkDebug();
  },

  checkDebug() {
    app.util.request({
      url: 'entry/wxapp/index',
      data: {
        op: 'checkSwitch',
      },
      module: 'cm_video_alarm',
      success: res => {
        if (res.data && res.data.errno == 0) {
          const data = res.data.data;
          if (data) {
            this.setData({ debug: data.is_debug == 1 });
          }
        }
      },
    });
  },

  getRoomId() {  // 获取roomID
    const { id = '' } = this.options;
    let createRoom = true;
    let time = new Date();

    app.util.request({
      url: 'entry/wxapp/consult',
      data: {
        op: 'consultStart',
        id,
      },
      module: 'cm_video_alarm',
      success: res => {
        const { roomid: roomID = '' } = res.data.data;
        time = time.getHours() + ':' + time.getMinutes() + ':' + time.getSeconds();
        console.log('*************开始多人音视频：' + time + '**************');

        this.getOnlineRoom().then(res => {
          const rooms = res.rooms;
          if (rooms.length > 0) {
            rooms.map(item => {
              if (item.roomID === roomID) {
                createRoom = false;
              }
            });
          }
          console.log('======================createRoom', createRoom);
          this.setData({
            roomID,
            roomname: '',
            username: '',
            showRoom: true,
            createRoom,
          }, function () {
            let rtcroomCom = this.selectComponent('#rtcroom');
            if (rtcroomCom) {
              rtcroomCom.start();
            }
          });
        });
      },
      faile: res => {
        wx.showModal({
          title: '系统提示',
          content: 'roomID获取失败',
          showCancel: false,
          success: (result) => {
            if (result.confirm) {
              wx.navigateBack();
            }
          },
        });
      },
    });
  },

  getOnlineRoom() {  // 获取在线房间
    return new Promise(resolve => {
      rtcroom.getRoomList({
        data: {
          index: 0,
          cnt: 20,
        },
        success: res => {
          resolve(res);
        },
        fail: res => {
          resolve([]);  // 失败默认为空
        },
      });
    });
  },

  versiongt: function (version1, version2) {
    var v1 = version1.split(".");
    var v2 = version2.split(".");
    if (parseInt(v1[0]) > parseInt(v2[0])) {
      return true;
    } else if (parseInt(v1[0]) == parseInt(v2[0])) {
      if (parseInt(v1[1]) > parseInt(v2[1])) {
        return true;
      } else if (parseInt(v1[1]) == parseInt(v2[1])) {
        if (parseInt(v1[2]) >= parseInt(v2[2])) {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    } else {
      return false;
    }
  }
});
